/**
 * Project Name:youba
 * Package Name:com.inoneone.youba.mcht.base.api
 * Date:2017/6/19下午4:54
 * Copyright (c) 2017, www.zbj.com All Rights Reserved
 */
package com.inoneone.youba.mcht.service.impl;

import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.inoneone.toolkit.exception.BusinessRuntimeException;
import com.inoneone.youba.mcht.cache.mapper.VerifyCodeMapper;
import com.inoneone.youba.mcht.cache.po.VerifyCodePo;
import com.inoneone.youba.mcht.conf.ValueConfig;
import com.inoneone.youba.mcht.enums.ErrorCode;
import com.inoneone.youba.mcht.enums.SmsTemplateCode;
import com.inoneone.youba.mcht.service.MsgCenterApi;
import com.inoneone.youba.mcht.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Description: 安全管理服务 </br>
 * Date: 2017/6/19下午4:54 </br>
 *
 * @author 姬远玄
 * @since JDK 1.7
 */
@Service
public class MsgCenterApiImpl implements MsgCenterApi {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    IAcsClient iAcsClient;

    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    static final String accessKeyId = "LTAIkkByqcEtGEMu";
    static final String accessKeySecret = "zxSidOS5xCihc3doDsPq9WwoFHSMyg";
    static final String signName = "油巴";


    @Autowired
    VerifyCodeMapper verifyCodeMapper;

    @Autowired
    ValueConfig valueConfig;


    /**
     * Description: 验证短信验证码</br>
     * Date: 2017-06-28 15:40:05</br>
     *
     * @param verifySessionId session
     * @param verifyCode      验证码
     * @return
     * @author 姬远玄
     * @since JDK 1.7
     */
    @Override
    public void verifySms(String verifySessionId, String verifyCode) {

        //获取缓存验证对象
        VerifyCodePo verifyCodePo = verifyCodeMapper.select(verifySessionId);

        //校验码过期时间
        long overTime = valueConfig.getVerifyExpireSec() * 1000;
        if (verifyCodePo.getInitTime() + overTime < System.currentTimeMillis()) {
            throw new BusinessRuntimeException(ErrorCode.SMS_OVERTIME);
        }

        //校验次数
        if (verifyCodePo.getVerifyCount() >= valueConfig.getVerifyMaxCount()) {
            throw new BusinessRuntimeException(ErrorCode.VERIFY_MAX_COUNT);
        }

        //校验验证码
        if (!verifyCodePo.getVerifyCode().equals(verifyCode)) {
            verifyCodePo.setVerifyCode(verifyCodePo.getVerifyCode() + 1);
            verifyCodeMapper.insertAndUpdate(verifyCodePo);
            throw new BusinessRuntimeException(ErrorCode.VERIFY_CODE_WRONG);
        }
    }

    /**
     * Description: 调用发送短信</br>
     * Date: 2017-08-28 14:26:45</br>
     *
     * @param
     * @return
     * @author 姬远玄
     * @since JDK 1.7
     */
    public void sendSms(String mobile, String templateCode, Map<String, String> map)
    {
        try {
            logger.debug("正在发送短信" + mobile);
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(mobile);
            request.setSignName(signName);
            request.setTemplateCode(templateCode);

            request.setTemplateParam(StringUtil.jsonFormat(map));
            SendSmsResponse sendSmsResponse = iAcsClient.getAcsResponse(request);
            logger.debug("短信接口返回[" + sendSmsResponse.getCode() + "]" + sendSmsResponse.getMessage());
            return;
        } catch (Exception e) {
            throw new BusinessRuntimeException(ErrorCode.SEND_SMS_ERR);
        }
    }

    @Override
    @Async
    /**
     * 短信验证码
     */
    public void sendVerifyPwd(String mobile, String code) {
        try {
            Map map = new HashMap<String, String>();
            map.put("code", code);
            sendSms(mobile, SmsTemplateCode.RESET_PWD.getCode(), map);
        } catch (Exception e) {
            throw new BusinessRuntimeException(ErrorCode.SEND_SMS_ERR);
        }
    }

    @Override
    @Async
    /**
     * 短信验证码
     */
    public void sendVerifyPayPwd(String mobile, String code) {
        try {
            Map map = new HashMap<String, String>();
            map.put("code", code);
            sendSms(mobile, SmsTemplateCode.RESET_PAY_PWD.getCode(), map);
        } catch (Exception e) {
            throw new BusinessRuntimeException(ErrorCode.SEND_SMS_ERR);
        }
    }

    @Override
    @Async
    /**
     * ic卡:{$cardId}在${time}产生了一笔加油消费，消费金额为${amount}元,如有疑问请立即登陆管理后台查看或者冻结当前ic卡
     */
    public void sendRiskSms(String mobile, String cardId, String dateTime, String amount) {
        Map map = new HashMap<String, String>();
        map.put("cardId", cardId);
        map.put("time", dateTime);
        map.put("amount", amount + "元");
        sendSms(mobile, SmsTemplateCode.MUCH_EXCEPTION.getCode(), map);
    }

    @Override
    @Async
    /**
     * ic卡:油巴加油卡[{$cardId}]的用户您好，油巴提醒您，您的油巴余额已经不足${amount}，请及时充值，以免耽误您的工作
     */
    public void sendBalanceLessSms(String mobile, String cardId, String amount) {
        Map map = new HashMap<String, String>();
        map.put("cardId", cardId);
        map.put("amount", amount + "元");
        sendSms(mobile, SmsTemplateCode.NO_BALANCE_TO_C.getCode(), map);
    }

    @Override
    @Async
    /**
     * 油巴提醒您，您管理的油巴加油卡[{$cardId}]余额已经不足${amount}，请及时通知对方充值。您还可以在油巴系统添加该卡的手机号，下次余额不足系统会直接通知对方！
     */
    public void sendBalanceLessSmsToMch(String mobile, String cardId, String amount) {
        Map map = new HashMap<String, String>();
        map.put("cardId", cardId);
        map.put("amount", amount + "元");
        sendSms(mobile, SmsTemplateCode.NO_BALANCE_TO_B.getCode(), map);
    }

    @Override
    @Async
    /**
     * ic卡:{$cardId}在${time}产生了一笔加油消费，距离上次消费间隔${min}，过于频繁,如有疑问请立即登陆管理后台查看或者冻结当前ic卡
     */
    public void sendIntervalRiskSms(String mobile, String cardId, String dateTime, String min) {
        Map map = new HashMap<String, String>();
        map.put("cardId", cardId);
        map.put("min", min + "秒");
        map.put("time", dateTime);
        sendSms(mobile, SmsTemplateCode.FREQ_EXCEPTION.getCode(), map);
    }
}
